import React, { useState, useEffect } from 'react';
import { ServeLogin } from './login';
import { CurModel, User } from 'cache';
import { cline, obj_str, BtImg, CenterView, uDb } from 'sui';

const ServeView = () => {
    const [line, setLine] = useState(null);
    const [single, setSingle] = useState(true);
    const [data_line, setDataline] = useState([]);

    useEffect(() => {
        User.LogOut();

        uDb(null, "setting/get", { line: cline() },
            r => {
                CurModel.set_ver(obj_str(r, "ver"));

                const lang = obj_str(r, "lang");
                if (lang) {
                    CurModel.set_lang(lang);
                }

                const ret = r["line"];

                if (ret.length === 1) {
                    const t = ret[0].id;

                    setLine(t);
                    setSingle(true);

                    CurModel.setLine(t);
                }
                else {
                    setDataline(ret);
                    setSingle(false);
                }
            },
            e => setDataline([])
        );
    }, []);

    const setCurline = (v) => {
        for (let i = 0; i < data_line.length; i++ ) {
            const d = data_line[i];
            if (d.id === v) {
                CurModel.setLineDes(d.desc ? d.desc : "");
                break;
            }
        }
        CurModel.setLine(v);
        setLine(v);
    };

    if (line) {
        return (<ServeLogin sig={single}/>);
    }
    else {
        const tmp = data_line.map((d, i) =>
            <BtImg
                name={d.id}
                key={d.id}
                hcmd={setCurline}
                src={`image/${d.id}.png`}>{d.desc}</BtImg>
        );

        return (
            <CenterView className="flex-wrap justify-around">
                {tmp}
            </CenterView>
        );
    }
};

export {ServeView};
